/*
 * Copyleft 2012 Power by Colen.
 *
 * Project: app-crm
 * Date: Mar 18, 2012
 */
package com.crm.business.web.auth.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.crm.business.web.auth.service.LoginoutService;
import com.crm.common.exception.CrmSysException;
import com.crm.common.web.controller.WebCommonController;

/**
 * Auth Login and logout Controller
 *
 * @author Colen
 *
 */
@Controller("auth_loginoutController")
public class LoginoutController extends WebCommonController {

    /** Logger */
    private static final Logger LOG = Logger.getLogger(LoginoutController.class);

    /**
     * login
     *
     * @param request http request
     * @param response http response
     */
    @RequestMapping("auth/login.shtm")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        LOG.info("login beging...");

        // request parameters
        Map<String, Object> params = getReqParams(request);

        /*
        String inputAuthCode = (String) params.get("auth_code");
        String realAuthCode = getCookieValue(request, "auth_code", true);
        if (!inputAuthCode.equalsIgnoreCase(realAuthCode)) {
            LOG.info("input error authcode : " + inputAuthCode);
            throw new BusinessException("验证码输入不正确啦！");
        }
        */

        // auth login check
        this.service.doAuthLogin(params);

        @SuppressWarnings("unchecked")
        Map<String, Object> user = (Map<String, Object>) params.get("user");
        // store
        setCookie(response, "uid", user.get("uid").toString(), -1, false);
        try {
            String uname = URLEncoder.encode(user.get("name").toString(), "utf-8");
            setCookie(response, "uname", uname, -1, false);
        } catch (UnsupportedEncodingException uee) {
            throw new CrmSysException("Unsupported Encoding Error!", uee);
        }
        // clear auth_code 
        // setCookie(response, "auth_code", "", 0, true);

        Map<String, Object> output = getDefaultResult();
        output.put("forward", "platform.shtm");
        outputJSON(response, output);

        LOG.info("login end.");
    }

    /**
     * open main page
     *
     * @return model and view
     */
    @RequestMapping("platform.shtm")
    public ModelAndView showMainPage() {
        return new ModelAndView("main/p00_main_main.jsp");
    }

    /** Main Service */
    @Resource(name = "auth_loginoutService")
    private LoginoutService service = null;
}
